package com.sun.juc.lock;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo01 {
    public static void main(String[] args) {
        Shar shar = new Shar();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shar.incrNumber();
            }},"AA").start();
        new Thread(()->{for (int i = 0; i < 10; i++) {
            shar.decrNumber();
        }},"BB").start();
    }
}
class Shar{
    private int number = 0;
    private  Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    //加1
    public  void incrNumber(){
        lock.lock();
        try{
            //判断
            while (number != 0){
                condition.await();
            }
            //干活
            number++;
            //通知
            System.out.println(Thread.currentThread().getName() + "::" + number);
            condition.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    //减1
    public  void decrNumber() {
        lock.lock();
        try {
            //判断
            while (number != 1) {
                condition.await();
            }
            //干活
            number--;
            //通知
            System.out.println(Thread.currentThread().getName() + "::" + number);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
